const db = require('../model')
const Pharmacy = db.pharmacy
const Op = db.Sequelize.Op

// 查询所有药店
exports.findAll = async (req, res) => {
	const { page, pageSize, cityIndex } = req.query

	if (cityIndex == 0 || cityIndex == 4) {
		const { rows, count } = await Pharmacy.findAndCountAll({
			where: {
				hot: 1,
			},
			raw: true,
			limit: pageSize * 1,
			offset: pageSize * (page - 1) * 1,
		})
		if (!rows) {
			return res.status(500).send({
				message: '没有相关的门店信息',
			}) //一定要return
		}
		return res.status(200).send({
			data: rows,
			count,
		})
	}

	let cityName = ''

	switch (cityIndex) {
		case '1':
			cityName = '北京'
			break
		case '2':
			cityName = '广州'
			break
		case '3':
			cityName = '上海'
			break
	}

	const { rows, count } = await Pharmacy.findAndCountAll({
		where: {
			pharmacyPlace: {
				[Op.like]: `%${cityName}%`,
			},
		},
		raw: true,
		limit: pageSize * 1,
		offset: pageSize * (page - 1) * 1,
	})
	if (!rows) {
		return res.status(500).send({
			message: '没有相关的门店信息',
		}) //一定要return
	}
	return res.status(200).send({
		data: rows,
		count,
	})
}
// 新增门店
exports.createOne = async (req, res) => {
	const {
		pharmacyId,
		pharmacyName,
		pharmacyPlace,
		pharmacyTimebeg,
		pharmacyTimeend,
	} = req.query
	const createData = UsersModel.create({
		pharmacyId,
		pharmacyName,
		pharmacyPlace,
		pharmacyTimebeg,
		pharmacyTimeend,
	})
	createData = await createData.save()
	if (!createData) {
		return res.status(404).end() //一定要return
	}
	return res.status(200).send({
		data, //和前端对应code
	})
}
//更新门店信息
exports.update = async (req, res) => {
	const {
		pharmacyId,
		pharmacyName,
		pharmacyPlace,
		pharmacyTimebeg,
		pharmacyTimeend,
		pharmacyNamenew,
		pharmacyPlacenew,
		pharmacyTimebegnew,
		pharmacyTimeendnew,
	} = req.query
	const updateData = await Pharmacy.findOne({
		where: {
			pharmacyId,
			pharmacyName,
			pharmacyPlace,
			pharmacyTimebeg,
			pharmacyTimeend,
		},
	})
	updateData.pharmacyName = pharmacyNamenew
	updateData.pharmacyPlace = pharmacyPlacenew
	updateData.pharmacyTimebeg = pharmacyTimebegnew
	updateData.pharmacyTimeend = pharmacyTimeendnew
	updateData.save()
	if (!updateData) {
		return res.status(404).end() //一定要return
	}
	return res.status(200).send({
		data, //和前端对应code
	})
}
//删除门店信息
exports.delete = async (req, res) => {
	const { pharmacyId } = req.query
	const deleteData = await Pharmacy.findOne({
		where: { pharmacyId },
	})
	await deleteData.destroy()
	if (!deleteData) {
		return res.status(404).end() //一定要return
	}
	return res.status(200).send({
		data, //和前端对应code
	})
}
